package xgenerator.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

public class JdbcTransaction implements Transaction {

	/**
	 * JDBC Connection
	 */
	private Connection conn;
	
	/**
	 * constructor
	 * @param conn JDBC Connection
	 */
	public JdbcTransaction(Connection conn) {
		if(null == conn) {
			throw new RuntimeException("JDBC Connection is null");
		}
		this.conn = conn;
	}

	/**
	 * <p>
	 * Title：判断事务是否有效
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @return
	 * @see xgenerator.jdbc.Transaction#isActive()
	 */
	public boolean isActive() {
		try {
			if(null != this.conn && !this.conn.isClosed()) {
				return true;
			}
		} catch (SQLException e) {
			return false;
		}
		return false;
	}

	/**
	 * <p>
	 * Title：begin
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @see xgenerator.jdbc.Transaction#begin()
	 */
	public void begin() {
		try {
			this.conn.setAutoCommit(false);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * <p>
	 * Title：Commit Transaction
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @see xgenerator.jdbc.Transaction#commit()
	 */
	public void commit() {
		try {
			this.conn.commit();
			this.conn.setAutoCommit(true);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * <p>
	 * Title：Rollback Transaction
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @see xgenerator.jdbc.Transaction#rollback()
	 */
	public void rollback() {
		try {
			this.conn.rollback();
			this.conn.setAutoCommit(true);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void addTransaction(Transaction transaction) {
		
	}
	
}
